package com.system.runtai.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 短信验证码发送相关工具类
 */
@Component
public class SmsVerificationUtils {

    /**
     * 阿里云 accessKeyId
     */
    @Value("${aliSms.accessKeyId}")
    private String accessKeyId;

    /**
     * 阿里云 secret
     */
    @Value("${aliSms.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 阿里云签名
     */
    @Value("${aliSms.signName}")
    private String signName;

    /**
     * 阿里云短信模板Code
     */
    @Value("${aliSms.templateCode}")
    private String templateCode;

    /**
     * Redis 工具类
     */
    @Autowired
    private RedisService redisService;

    /**
     * 从Redis中根据手机号获取验证码
     *
     * @param key 手机号
     * @return 返回获取的验证码
     */
    public String get(String key) {
        Object code = redisService.get(key);
        if (code != null) {
            return redisService.get(key).toString();
        }
        return null;
    }

    /**
     * 删除Redis中的验证码
     *
     * @param key 手机号
     */
    public void delete(String key) {
        redisService.del(key);
    }


    /**
     * 发送短信手机短信验证码
     *
     * @param phoneNum 手机号
     * @return 返回发送状态
     */
    public String send(String phoneNum) {

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        Random random = new Random();
        String randomNumber = String.valueOf(random.nextInt(9000) + 1000);
        CommonRequest request = new CommonRequest();
        request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\": " + randomNumber + "}");

        try {
//            // 将验证码放入Redis缓存中  有效时间为5分钟
//            boolean set = redisService.set(phoneNum, randomNumber, 300);
//            if (!set) {
//                return "Redis存入失败";
//            }
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            return JSONObject.parseObject(data).getString("Message");
        } catch (ServerException e) {
            e.printStackTrace();
            return null;
        } catch (ClientException e) {
            e.printStackTrace();
            return null;
        }

    }


    /**
     * 验证码校验
     *
     * @param phoneNumber 手机号
     * @param code        用户输入的验证码
     * @return 返回校验结果
     */
    public String check(String phoneNumber, String code) {
        String verification = this.get(phoneNumber);
        // 手机号不存在,从新发送验证码
        if (verification == null) {
            return null;
        }
        if (verification.equals(code)) {
            //  校验通过后删除Redis中的验证码缓存
            this.delete(phoneNumber);
            return "OK";
        }
        // 验证码校验错误
        return "ERROR";

    }

    public static void main(String[] args) {
        String phone = "15511241824";
        SmsVerificationUtils smsVerificationUtils = new SmsVerificationUtils();
        String send = smsVerificationUtils.send(phone);

//        String check = smsVerificationUtils.check(phone, send);

//        System.out.println("check = " + check);

        System.out.println(send);
    }
}
